const ToolPageConfig = require("./ToolPageConfig");
const pages = require("./pages");
const fs = require('fs');
const path = "../../pages.json";

function listFiles(path, parentPath = "") {
	let files = fs.readdirSync(path);
	if (!files || files.length < 1) {
		return [];
	}
	let filePaths = [];
	files.forEach(item => {
		let filePath = `${path}/${item}`;
		let file = fs.statSync(filePath);
		if (file.isFile()) {
			if (".vue" === filePath.substr(-4)) {
				if (!pages.pages.map(item => item.path).includes(filePath.substring(6, filePath.length - 4))) {
					filePaths.push({
						path: filePath.substring(6 + parentPath.length, filePath.length - 4)
					});
				}
			}
		} else {
			filePaths.push({
				path: filePath.substring(6 + parentPath.length),
				children: listFiles(filePath, filePath.substring(6))
			})
		}
	})
	return filePaths;
}

let paths = listFiles("../../pages");

console.log(paths);

function buildChildren(paths, parentPath = "") {
	let childrens = [];
	paths.forEach(item => {
		if (item.children) {
			childrens = [...childrens, ...buildChildren(item.children, `${parentPath}${item.path}`)]
		} else {
			childrens.push(ToolPageConfig.layout(`${parentPath}${item.path}`.substr(1)));
		}
	})
	return childrens;
}

fs.readFile(path, function(err, data) {
	if (err) {
		return console.error(err);
	}
	
	pages.subPackages = [];

	paths.forEach(item => {
		pages.subPackages.push({
			root: item.path,
			pages: buildChildren(item.children)
		})
	})

	// 清空底部 tabbar
	fs.writeFile(path, JSON.stringify(pages), function(err) {
		if (err) {
			console.error(err);
		}
		console.log('----------全局配置修改成功-------------');
	});
});
